var Wechat = {
    token: null,
    to: null,
    message: null,
    parse_mode: null,

    sendMessage: function() {
        var params = {
            msgtype: "text",
            chat_id: Wechat.to,
            text: {
                content:Wechat.message
            },
            disable_web_page_preview: true,
            disable_notification: false
        },
        data,
        response,
        request = new CurlHttpRequest(),
        url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=' + Wechat.token;

        if (Wechat.parse_mode !== null) {
            params['parse_mode'] = Wechat.parse_mode;
        }

        request.AddHeader('Content-Type: application/json');
        data = JSON.stringify(params);

        // Remove replace() function if you want to see the exposed token in the log file.
        Zabbix.Log(4, '[Wechat Webhook] URL: ' + url.replace(Wechat.token, '<TOKEN>'));
        Zabbix.Log(4, '[Wechat Webhook] params: ' + data);
        response = request.Post(url, data);
        Zabbix.Log(4, '[Wechat Webhook] HTTP code: ' + request.Status());
        Zabbix.Log(4, '[Wechat Webhook] response: ' + response);

        try {
            response = JSON.parse(response);
        }
        catch (error) {
            response = null;
            Zabbix.Log(4, '[Wechat Webhook] response parse error');
        }

        if (request.Status() !== 200 ||  response.errcode !== 0 || response.errmsg !== 'ok') {
            if (typeof response.errmsg === 'string') {
                throw response.errmsg;
            }
            else {
                throw 'Unknown error. Check debug log for more information.'
            }
        }
    }
}

try {
    var params = JSON.parse(value);

    if (typeof params.Token === 'undefined') {
        throw 'Incorrect value is given for parameter "Token": parameter is missing';
    }

    Wechat.token = params.Token;

    if (['Markdown', 'HTML', 'MarkdownV2'].indexOf(params.ParseMode) !== -1) {
        Wechat.parse_mode = params.ParseMode;
    }

    Wechat.to = params.To;
    Wechat.message = params.Subject + '\n' + params.Message;
    Wechat.sendMessage();

    return 'OK';
}
catch (error) {
    Zabbix.Log(4, '[Wechat Webhook] notification failed: ' + error);
    throw 'Sending failed: ' + error + '.';
}